package com.pug.web.sms;

import com.pug.annotation.EnableNoToken;
import com.pug.constant.PugContants;
import com.pug.service.sms.SmsService;
import com.pug.utils.fn.asserts.Vsserts;
import com.pug.utils.ip.IpUtils;
import com.pug.utils.valid.ValidatorUtil;
import com.pug.web.BaseController;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/3/16$ 23:56$
 */
@RestController
@RequiredArgsConstructor
public class PassportSMSSendController extends BaseController implements PugContants {
    @Resource
    SmsService smsService;
    @Resource
    RedisTemplate<String,String> redisTemplate;
    @EnableNoToken(true)
    @PostMapping("/passport/smssend/{phone}")
    public String sendPhoneCode(@PathVariable("phone") String phone, HttpServletRequest request) {
        Vsserts.isEmptyEx(phone, "请输入手机号码");
        Vsserts.isFalse(ValidatorUtil.isValidatorPhone(phone),"请输入正确的手机号码");
        // 1: 生成一个发送短信的随机数
        String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
        System.out.println(code);
//        String code="mua~~~";
        // 2: 发送短信的接口  //发送成功为ture 失败则为false
//        boolean sendSMS = smsService.sendSMS(phone, code);
        // 把生成的验证码放入到redis缓存中，用于后续的验证
        redisOperator.set(PUG_XQ_LOGIN_SMS_CODE + phone, code,60);
        //获取发短信的ip地址，防止重复发送
        String ipAddr = IpUtils.getIpAddr(request);
        redisOperator.set(PUG_IP+ipAddr, ipAddr,60);
        // 发送短信成功
        return "success";
    }
}
